
package com.wobaby.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import com.wobaby.util.config.Config;

// Referenced classes of package com.wobaby.util:
//            VariableNotFoundException

public class StringUtils
{

    public StringUtils()
    {
    }

    public static String[] tokenize(String text, String separator)
    {
        ArrayList list = new ArrayList();
        String token;
        for(StringTokenizer st = new StringTokenizer(text, separator); st.hasMoreTokens(); list.add(token.trim()))
            token = st.nextToken();

        return (String[])(String[])list.toArray(new String[list.size()]);
    }

    public static String[] explode(String text)
    {
        ArrayList list = new ArrayList(50);
        int size = text.length();
        int previousLocation = 0;
        int iloop;
        for(iloop = 0; iloop < size; iloop++)
        {
            char c = text.charAt(iloop);
            if(c == '\n')
            {
                list.add(text.substring(previousLocation, iloop + 1));
                previousLocation = iloop + 1;
            }
        }

        if(previousLocation != iloop)
            list.add(text.substring(previousLocation));
        return (String[])(String[])list.toArray(new String[list.size()]);
    }

    public static Integer[] explodeInts(String list)
    {
        String numbers[] = list.split(",");
        Integer ints[] = new Integer[numbers.length];
        for(int n = 0; n < numbers.length; n++)
            ints[n] = new Integer(numbers[n]);

        return ints;
    }

    public static int[] explodeIntegers(String list)
    {
        String numbers[] = list.split(",");
        int ints[] = new int[numbers.length];
        for(int n = 0; n < numbers.length; n++)
            ints[n] = Integer.parseInt(numbers[n]);

        return ints;
    }

    public static Long[] explodeLongs(String list)
    {
        String numbers[] = list.split(",");
        Long ints[] = new Long[numbers.length];
        for(int n = 0; n < numbers.length; n++)
            ints[n] = new Long(numbers[n]);

        return ints;
    }

    public static String implode(String lines[])
    {
        return implode(lines, null);
    }

    public static String implode(String lines[], String lineSeparator)
    {
        if(lines == null)
            return "";
        StringBuffer sb = new StringBuffer(lines.length * 40 + 1);
        for(int i = 0; i < lines.length; i++)
        {
            sb.append(lines[i]);
            if(lineSeparator != null)
                sb.append(lineSeparator);
        }

        return sb.toString();
    }

    public static String implode(Integer lines[])
    {
        return implode(lines, null);
    }

    public static String implode(Integer lines[], String lineSeparator)
    {
        if(lines == null)
            return "";
        StringBuffer sb = new StringBuffer(lines.length * 40 + 1);
        for(int i = 0; i < lines.length; i++)
        {
            sb.append(lines[i]);
            if(lineSeparator != null)
                sb.append(lineSeparator);
        }

        return sb.toString();
    }

    public static String implode(List lines)
    {
        return implode(lines, null);
    }

    public static String implode(List lines, String lineSeparator)
    {
        StringBuffer sb = new StringBuffer(lines.size() * 40 + 1);
        for(int i = 0; i < lines.size(); i++)
        {
            Object o = lines.get(i);
            if(o == null)
                o = "";
            sb.append(o);
            if(lineSeparator != null)
                sb.append(lineSeparator);
        }

        return sb.toString();
    }

    public static String unite(String lines[], char separator)
    {
        if(lines == null)
            return "";
        StringBuffer sb = new StringBuffer(lines.length * 40 + 1);
        for(int i = 0; i < lines.length; i++)
        {
            sb.append(lines[i]);
            if(i + 1 < lines.length)
                sb.append(separator);
        }

        return sb.toString();
    }

    public static String unite(Collection objects, char separator)
    {
        if(objects == null)
            return "";
        StringBuffer sb = new StringBuffer(objects.size() * 32);
        Iterator i = objects.iterator();
        do
        {
            if(!i.hasNext())
                break;
            sb.append(i.next());
            if(i.hasNext())
                sb.append(separator);
        } while(true);
        return sb.toString();
    }

    public static String capitalize(String word)
    {
        if(word == null || word.length() == 0)
            return word;
        if(word.length() == 1)
            return Character.toUpperCase(word.charAt(0)) + "";
        else
            return Character.toUpperCase(word.charAt(0)) + word.substring(1);
    }

    public static String uncapitalize(String word)
    {
        if(word == null || word.length() == 0)
            return word;
        if(word.length() == 1)
            return Character.toLowerCase(word.charAt(0)) + "";
        else
            return Character.toLowerCase(word.charAt(0)) + word.substring(1);
    }

    public static String replaceControlChars(String s)
    {
        byte b[] = s.getBytes();
        int escapeCount = 0;
        for(int iloop = 0; iloop < b.length; iloop++)
            if(b[iloop] < 32)
                escapeCount++;

        byte bOut[] = new byte[b.length + escapeCount];
        int byteCount = 0;
        for(int iloop = 0; iloop < b.length; iloop++)
            if(b[iloop] > 31 || b[iloop] == 10 || b[iloop] == 13)
            {
                bOut[byteCount] = b[iloop];
                byteCount++;
            } else
            {
                bOut[byteCount] = 94;
                bOut[byteCount + 1] = (byte)(b[iloop] + 64);
                byteCount += 2;
            }

        return new String(bOut, 0, byteCount);
    }

    public static String unescape(String val)
    {
        if(val.indexOf("\\") < 0)
            return val;
        StringBuffer valb = new StringBuffer(32);
        valb.append(val);
        int insertIndex = 0;
        for(int lookIndex = 0; lookIndex < valb.length(); lookIndex++)
        {
            char currentChar = valb.charAt(lookIndex);
            if(currentChar == '\\' && lookIndex + 1 < valb.length())
            {
                char nextChar = valb.charAt(lookIndex + 1);
                int skip = 1;
                switch(nextChar)
                {
                case 110: // 'n'
                    currentChar = '\n';
                    break;

                case 114: // 'r'
                    currentChar = '\r';
                    break;

                case 116: // 't'
                    currentChar = '\t';
                    break;

                case 120: // 'x'
                    if(lookIndex + 3 < valb.length())
                    {
                        String hexValue = String.valueOf(valb.charAt(lookIndex + 2)) + String.valueOf(valb.charAt(lookIndex + 3));
                        currentChar = (char)Integer.parseInt(hexValue, 16);
                        skip = 3;
                    } else
                    {
                        skip = 0;
                    }
                    break;

                case 92: // '\\'
                    currentChar = '\\';
                    break;

                case 36: // '$'
                    currentChar = '$';
                    break;

                default:
                    skip = 0;
                    break;
                }
                lookIndex += skip;
            }
            valb.setCharAt(insertIndex++, currentChar);
        }

        valb.setLength(insertIndex);
        return valb.toString();
    }

    public static String fillLeadingZero(int number, int desiredWidth)
    {
        String ret = "" + number;
        int width = ret.length();
        for(int i = 0; i < desiredWidth - width; i++)
            ret = "0" + ret;

        return ret;
    }

    public static String fillLeadingZero(String ret, int desiredWidth)
    {
        int width = ret.length();
        for(int i = 0; i < desiredWidth - width; i++)
            ret = "0" + ret;

        return ret;
    }

/*    public static String pad(String ip)
    {
        return IPUtils.pad(ip);
    }

    public static String unpad(String ip)
    {
        return IPUtils.normalize(ip);
    }*/

 /*   public static String replaceVars(String body, Map vars, int i, boolean notFoundError)
    {
        StringBuffer result = new StringBuffer();
        StringTokenizer toker = new StringTokenizer(body, "$", true);
        do
        {
            if(!toker.hasMoreTokens())
                break;
            String tok = toker.nextToken();
            if(tok.equals("$"))
            {
                if(!toker.hasMoreTokens())
                    break;
                String name = toker.nextToken();
                if(!toker.hasMoreTokens())
                    break;
                String variable = tok + name + toker.nextToken();
                List values = (List)vars.get(variable);
                if(values == null)
                {
                    if(notFoundError)
                        throw new VariableNotFoundException(variable);
                    result.append(variable);
                } else
                {
                    result.append(values.get(i));
                }
            } else
            {
                result.append(tok);
            }
        } while(true);
        return result.toString();
    }*/

    public static String stripPackageName(String fullName)
    {
        int index = fullName.lastIndexOf(".");
        if(index < 0)
            return fullName;
        else
            return fullName.substring(index + 1);
    }

    public static String stripWildcards(String s)
    {
        if(s == null || s.trim().length() == 0)
            return s;
        for(s = s.trim(); s.length() > 0 && (s.charAt(0) == '*' || s.charAt(0) == '?'); s = s.substring(1));
        for(; s.length() > 0 && (s.charAt(s.length() - 1) == '*' || s.charAt(s.length() - 1) == '?'); s = s.substring(0, s.length() - 1));
        return s;
    }

    public static String htmlEncode(String input)
    {
        if(input == null || input.length() == 0)
            return input;
        StringBuffer sb = new StringBuffer(input.length() + 100);
        int ilen = input.length();
        for(int iloop = 0; iloop < ilen; iloop++)
        {
            char c = input.charAt(iloop);
            switch(c)
            {
            case 38: // '&'
                if(iloop + 2 < ilen && input.charAt(iloop + 1) == '#')
                    sb.append(c);
                else
                    sb.append("&amp;");
                break;

            case 62: // '>'
                sb.append("&gt;");
                break;

            case 60: // '<'
                sb.append("&lt;");
                break;

            case 34: // '"'
                sb.append("&quot;");
                break;

            default:
                sb.append(c);
                break;
            }
        }

        return sb.toString();
    }

/*    public static String urlEncode(String input)
    {
        try
        {
            return URLEncoder.encode(input, I18NHelper.getCharacterEncoding());
        }
        catch(UnsupportedEncodingException uee)
        {
            return input;
        }
    }*/

    public static String hexDump(String raw, int toKeep)
    {
        byte rawArray[] = raw.getBytes();
        String out = "";
        for(int index = 0; index < rawArray.length; index++)
        {
            byte rawChar = rawArray[index];
            boolean codeIt = false;
            if(rawChar >= 0 && rawChar <= 32 || rawChar >= 127)
            {
                codeIt = true;
                if(rawChar == 8 && (toKeep & 8) != 0)
                    codeIt = false;
                else
                if(rawChar == 32 && (toKeep & 4) != 0)
                    codeIt = false;
                else
                if(rawChar == 10 && (toKeep & 2) != 0)
                    codeIt = false;
                else
                if(rawChar == 13 && (toKeep & 1) != 0)
                    codeIt = false;
            }
            if(codeIt)
                out = out + "\\x" + Integer.toHexString(rawChar);
            else
                out = out + (char)rawChar;
        }

        return out;
    }

    public static String encodeExpectVar(String var)
    {
        if(var == null)
        {
            return "";
        } else
        {
            var = var.trim();
            var = var.replaceAll(" ", "\\\\x20");
            var = var.replaceAll("\"", "\\\\x22");
            var = var.replaceAll("#", "\\\\x23");
            var = var.replaceAll("\\$", "\\\\x24");
            var = var.replaceAll("\\+", "\\\\x2b");
            var = var.replaceAll(",", "\\\\x2c");
            var = var.replaceAll(":", "\\\\x3a");
            var = var.replaceAll("=", "\\\\x3d");
            return var;
        }
    }

    public static String decodeExpectVar(String var)
    {
        var = var.replaceAll("\\\\x20", " ");
        var = var.replaceAll("\\\\x22", "\"");
        var = var.replaceAll("\\\\x23", "#");
        var = var.replaceAll("\\\\x24", "\\$");
        var = var.replaceAll("\\\\x2b", "\\+");
        var = var.replaceAll("\\\\x2c", ",");
        var = var.replaceAll("\\\\x3a", ":");
        var = var.replaceAll("\\\\x3d", "=");
        return var;
    }

    public static int countOccurrences(String s, char c)
    {
        int index = -1;
        int count;
        for(count = 0; (index = s.indexOf(c, index + 1)) >= 0; count++);
        return count;
    }

    public static String replaceIllegalChar(String str)
    {
        char damnchar = '\003';
        char replacement = Config.getConfig().get("cisco_banner_control_char", "^").charAt(0);
        return str.replace(damnchar, replacement);
    }

/*    public static String formatMacAddress(String macAddr)
    {
        StringBuffer result = new StringBuffer(macAddr.length() * 2);
        int grouping = Config.getConfig().get("MacAddress/format/grouping", 2);
        String separator = Config.getConfig().get("MacAddress/format/separator", "-");
        boolean separatorBlank = separator.length() == 0;
        boolean lowcase = Config.getConfig().get("MacAddress/format/lowercase", false);
        int start = 0;
        int left = macAddr.length();
        for(; start < macAddr.length(); start += grouping)
        {
            if(grouping > left)
                grouping = left;
            String group = macAddr.substring(start, start + grouping);
            if(lowcase)
                group = group.toLowerCase();
            result.append(group);
            left -= grouping;
            if(!separatorBlank && left > 0)
                result.append(separator);
        }

        return result.toString();
    }*/

    public static String stripRealm(String ip)
    {
        if(ip == null)
            return null;
        int at = ip.indexOf("@");
        if(at == -1)
            return ip;
        else
            return ip.substring(0, at);
    }

    public static String chomp(String s)
    {
        for(int i = s.length(); i > 0; i--)
        {
            char c = s.charAt(i - 1);
            if(!isLineTerminator(c))
                return s.substring(0, i);
        }

        return "";
    }

    public static String blankIfNull(Object o)
    {
        return o != null ? o.toString() : "";
    }

    public static boolean isEmpty(String s)
    {
        return s == null || "".equals(s);
    }

    public static String appendListValueToText(List list)
    {
        StringBuffer sb = new StringBuffer();
        if(list != null)
        {
            for(int i = 0; i < list.size(); i++)
                sb.append(chomp((String)list.get(i)));

        }
        return sb.toString();
    }

    public static String trimPreceding( String str)
    {
    	if( str == null)
    		return null;
    	int len = str.length();
    	int index = 0;
    	for( index = 0; index < len; index++)
    	{
    		if( ! Character.isWhitespace( str.charAt( index )))
    			break;
    	}
    	return str.substring( index, len);
    } 
    public static boolean isLineTerminator(char c)
    {
        if(c == '\n')
            return true;
        if(c == '\r')
            return true;
        if(c == '\205')
            return true;
        if(c == '\u2028')
            return true;
        return c == '\u2029';
    }

    public static final int KEEP_ALL = 0;
    public static final int KEEP_CR = 1;
    public static final int KEEP_LF = 2;
    public static final int KEEP_SPACE = 4;
    public static final int KEEP_TAB = 8;
}